package com.imax.center.receive;

import com.imax.center.constant.QueueConstant;
import com.imax.center.service.DeviceDataService;
import com.imax.center.utils.TcpDataUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * 统一消费MQ队列数据
 * Author: luobenxi
 * CreateTime: 2025-06-20 23:45:10
 */
@Service
@Slf4j
public class ReceiveMQ {

    @Autowired
    DeviceDataService deviceDataService;

    @RabbitListener(queues = QueueConstant.SENSOR_EVENT_QUEUE)
    public void sensorEventReceive(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws InterruptedException, IOException {
        //判断message是否为##开头
        if (message.startsWith("##")) {
            Map<String, Object> data = TcpDataUtil.parseData(message);
            deviceDataService.syncHandlerEvent(message, data);
            // 手动确认消息
            channel.basicAck(deliveryTag, false);
            Thread.sleep(200); // 等待
        } else {
            log.info("报文格式错误: {}", message);
        }
    }

}
